package com.bilibili.controller;

import com.bilibili.entity.UserFollowingGroup;
import com.bilibili.enumeration.GroupType;
import com.bilibili.form.SettingFollowingForm;
import com.bilibili.service.FollowingService;
import com.bilibili.service.UserFollowingGroupService;
import io.mybatis.mapper.example.Example;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.stream.Streams;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "用户关注管理")
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/following")
public class UserFollowingController {

    private final UserFollowingGroupService userFollowingGroupService;
    private final FollowingService followingService;


    @ApiOperation("关注")
    @PostMapping("/{followingUserId}")
    public String following(@ApiParam(value = "关注用户ID", required = true) @NotBlank(message = "关注用户ID不能为空") @PathVariable Long followingUserId){
        Example<UserFollowingGroup> example = new Example<>();
        example.createCriteria().andEqualTo(UserFollowingGroup::getType, GroupType.DEFAULT.getCode());
        UserFollowingGroup userFollowingGroup = userFollowingGroupService.findOne(example);
        List<Long> groupIds = Streams.of(userFollowingGroup.getId()).collect(Collectors.toList());
        followingService.addFollow(1L, followingUserId, groupIds);
        return "";
    }

    @ApiOperation("取消关注")
    @DeleteMapping("/cancel/{followingUserId}")
    public String cancelFollowing(@ApiParam(value = "关注用户ID", required = true) @NotBlank(message = "关注用户ID不能为空") @PathVariable Long followingUserId){
        followingService.removeFollow(1L, followingUserId);
        return "";
    }

    @ApiOperation("设置分组")
    @PostMapping("/settingFollowingGroup")
    public String settingFollowingGroup(@ApiParam(value = "关注用户表单", required = true) @Valid @RequestBody SettingFollowingForm form){
        followingService.addFollow(1L, form.getFollowingUserId(), form.getGroupIds());
        return "";
    }

    @ApiOperation("创建分组")
    @PostMapping("/createFollowingGroup")
    public String createFollowingGroup(@ApiParam(value = "分组名称", required = true) @NotBlank(message = "分组名称不能为空") @RequestParam String groupName){
        userFollowingGroupService.createGroup(1L, groupName);
        return "";
    }

    @ApiOperation("删除分组")
    @DeleteMapping("/group/{groupId}")
    public String deleteFollowingGroup(@ApiParam(value = "分组ID", required = true) @NotBlank(message = "分组ID不能为空") @PathVariable Long groupId){
        userFollowingGroupService.deleterGroup(groupId);
        return "";
    }

}
